package com.joeyzh.demo;

import android.app.Activity;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.google.gson.JsonElement;
import com.google.gson.JsonIOException;
import com.joey.base.util.FileUtil;
import com.joey.base.util.LogUtils;
import com.joey.base.util.PermissionManager;
import com.joey.protocol.DownloadResponseListener;
import com.joey.protocol.ErrorListener;
import com.joey.protocol.JSONResponseListener;
import com.joey.protocol.NetClient;
import com.joey.protocol.NetClientConfig;
import com.joey.protocol.ResponseError;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * Created by Joey on 2018/3/21.
 */

public class NetActivity extends AppCompatActivity {

    TextView tvResponse;
    ProgressBar pbBar;
    private String url = "http://alp.joeyzh.com:8081/home/GetAreaByCheckUser?temp=getAreaManagerByAPP";

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.net_activity_main);
        tvResponse = findViewById(R.id.tv_response);
        pbBar = findViewById(R.id.progress_bar);
        NetClientConfig.I().format("Success", "Result", "ReturnMsg").
                initSuccessKey("true");
        if (PermissionManager.checkPermisson(this, com.joey.base.util.Permission.STORAGE)) {

        }
        NetClientConfig.I().setLogged(true);

        NetClientConfig.I().setErrorListener(new ErrorListener() {
            @Override
            public boolean onError(ResponseError error) {
                new AlertDialog.Builder(NetActivity.this)
                        .setTitle(error.getStatus())
                        .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                            }
                        })
                        .setMessage(error.getMessage()).create().show();
                return true;
            }
        });
    }

    public void send(View view) {
        switch (view.getId()) {
            case R.id.btn_json:
                postJson();
                break;
            case R.id.btn_download:
                download();
                break;
            case R.id.btn_upload:
                uploadFile();
                break;

        }
    }

    private void postJson() {
        NetClient client = new NetClient();
        Map<String, String> map = new HashMap<>();
        map.put("json", "{\"userName\":\"admin\",\"passWord\":\"pmQP2018\"}");
//        map.put("jsonData", "{\"Type\":\"MaintenanceType,InspectionResultType\"}");
//        client.httpPost("http://10.20.3.69:12306/api/Equipment/GetTypeInfo", map, new JSONResponseListener<JsonElement>() {
        client.httpPost("http://192.168.1.150:8089/pm_cloud/loginByUserIdApp1.action", map, new JSONResponseListener<JsonElement>() {
            @Override
            public void onResponse(JsonElement result, ResponseError error) {
                tvResponse.setText(result.toString());
            }

            @Override
            public void onError(ResponseError error) {
                tvResponse.setText(error.getMessage());
            }

            //     模拟自定义返回数据测试
            @Override
            public String getTestResponse() {
                return "{\"Result\":\"读取错误，请检查文件名！\",\"Success\":false,\"ReturnMsg\":\"读取错误，请检查文件名！\"}";
            }

            @Override
            public boolean isDebug() {
                return true;
            }
        });
    }

    private void download() {
        NetClient client = new NetClient();
        String url = "http://192.168.1.101:43380/PmCloud.apk";
        UserEntity entity = new UserEntity("admin", "123456");
        List<UserEntity> list = new ArrayList<>();
        list.add(entity);
        Map<String, Object> map = new HashMap<>();
        map.put("Json", list);
//        map.put("AccountID", "jwj");
//        map.put("Password", "123456");
        String savePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/PmCloud.apk";
        client.httpJsonPost(url, map, new DownloadResponseListener(savePath) {
            @Override
            public void onProgress(long total, long progress, float percent) {
                LogUtils.i("download", "total = " + total + ",progress = " + progress);
                pbBar.setMax((int) total);
                pbBar.setProgress((int) progress);
                tvResponse.setText((int) percent + "%");
            }

            @Override
            public void onError(ResponseError error) {
                LogUtils.e("download", "error:" + error.getMessage());

            }

            @Override
            public void onSuccess(File file, ResponseError error) {
                Log.e("download", "success");
            }
        });
    }


    private void uploadFile() {
        NetClient client = new NetClient();
        String url = "http://192.168.1.150:8089/pm_cloud/saveExceptionApp.action";
        Map<String, String> map = new HashMap<>();
        map.put("json", "{\"submitUserId\": \"1\",  \"isAnonymous\":\"\", \"exceptionType\":\"2\",\"deptId\":\"100000\",\"sectionId\":\"100001\",\"exceptionRemarks\":\"周晔上传的测试数据\",\"status\":\"1\"}");
        File file = new File(FileUtil.getExternalStorePath() + "/aaaa.jpg");
        client.uploads(url, map, new JSONResponseListener<JsonElement>() {
            @Override
            public void onResponse(JsonElement jsonElement, ResponseError responseError) throws JsonIOException {
                tvResponse.setText("上传成功！");
                pbBar.setMax(0);
                pbBar.setProgress(0);
            }

            @Override
            public void onError(ResponseError responseError) {

            }

            @Override
            public void onSink(long total, long progress, float percent, int index) {
//                LogUtils.e("upload", "total = " + total + ",progress = " + progress);
                pbBar.setMax((int) total);
                pbBar.setProgress((int) progress);
                tvResponse.setText("第" + index + "张：" + (int) percent + "%");
            }
        }, file, file, file, file, file, file);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return super.onCreateOptionsMenu(menu);
    }
}
